<template>
  <div class="role-management">
    <el-card shadow="never">
      <!-- 顶部工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-input
            v-model="query.keyword"
            placeholder="搜索角色名称/编码"
            style="width: 200px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
        </div>

        <div class="toolbar-right">
          <el-button @click="refreshTable">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 角色表格 -->
      <el-table :data="roleList" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色编码" width="150" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getRoleStatusTagType(scope.row.status)" size="small">
              {{ getRoleStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" text @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="warning" size="small" text @click="handlePermission(scope.row)">
              <el-icon><Setting /></el-icon>
              权限
            </el-button>
            <el-button type="danger" size="small" text @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="query.page"
          v-model:page-size="query.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="formModel.name" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色编码" prop="code">
              <el-input v-model="formModel.code" placeholder="请输入角色编码">
                <template #append>
                  <el-button @click="autoGenerateCode">自动生成</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number
                v-model="formModel.sort"
                :min="0"
                :max="999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色状态" prop="status">
              <el-radio-group v-model="formModel.status">
                <el-radio :value="true">启用</el-radio>
                <el-radio :value="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="角色描述">
          <el-input
            v-model="formModel.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="formModel.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      :title="`设置权限 - ${currentRole?.name}`"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="permission-container">
        <div class="permission-header">
          <el-alert
            title="权限说明"
            description="请选择该角色可以访问的菜单权限，未选择的菜单将无法访问"
            type="info"
            :closable="false"
            show-icon
          />
        </div>

        <div class="permission-tree">
          <el-tree
            ref="permissionTreeRef"
            :data="menuTreeData"
            :props="treeProps"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedMenuIds"
            :default-expand-all="true"
            highlight-current
          >
            <template #default="{ data }">
              <div class="tree-node">
                <el-icon v-if="data.icon" class="menu-icon">
                  <component :is="getIconComponent(data.icon)" />
                </el-icon>
                <span>{{ data.name }}</span>
                <el-tag v-if="data.menuType" size="small" type="info" style="margin-left: 8px;">
                  {{ getMenuTypeText(data.menuType) }}
                </el-tag>
              </div>
            </template>
          </el-tree>
        </div>
      </div>

      <template #footer>
        <el-button @click="handlePermissionCancel">取消</el-button>
        <el-button type="primary" @click="handlePermissionSave" :loading="permissionSaveLoading">
          保存权限
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  Setting
} from '@element-plus/icons-vue'

// 导入角色API
import {
  getRoleList,
  addRole,
  updateRole,
  deleteRole,
  getRoleMenuIds,
  setRoleMenu,
  getRoleStatusText,
  getRoleStatusTagType,
  transformToFormData,
  validateRoleCode,
  generateDefaultRoleCode,
  type Role,
  type RoleForm,
  type RoleListParams
} from '@/api/role'

// 导入菜单API（用于权限分配）
import {
  getMenuNodes,
  getMenuTypeText,
  type MenuItem
} from '@/api/menu'

// 图标组件映射
import {
  House, Setting as SettingIcon, User, Menu, Document, Monitor, View, Connection,
  Grid, Folder, Files, DataBoard, Management
} from '@element-plus/icons-vue'

const iconComponents = {
  House,
  Setting: SettingIcon,
  User,
  Menu,
  Document,
  Monitor,
  View,
  Connection,
  Grid,
  Folder,
  Files,
  DataBoard,
  Management
}

// 获取图标组件
const getIconComponent = (iconName: string) => {
  return iconComponents[iconName as keyof typeof iconComponents] || SettingIcon
}

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const permissionSaveLoading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const dialogTitle = ref('新增角色')
const isAdd = ref(true)
const total = ref(0)

const query = reactive({
  keyword: '',
  page: 1,
  size: 10
})

const roleList = ref<Role[]>([])
const currentRole = ref<Role | null>(null)
const menuTreeData = ref<MenuItem[]>([])
const checkedMenuIds = ref<number[]>([])

// 表单数据
const emptyForm: RoleForm = {
  name: '',
  code: '',
  description: '',
  status: true,  // 默认为启用状态
  sort: 0,
  remark: ''
}

const formModel = reactive<RoleForm>({ ...emptyForm })

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!validateRoleCode(value)) {
          callback(new Error('角色编码只能包含字母、数字和下划线，且不能以数字开头'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  sort: [
    { required: true, message: '请输入显示排序', trigger: 'blur' }
  ]
}

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 表单引用
const formRef = ref<FormInstance>()
const permissionTreeRef = ref()

// 业务方法
const fetchRoleData = async () => {
  loading.value = true
  console.log('🔍 开始获取角色数据...')

  try {
    // 构建查询参数
    const params: RoleListParams = {
      PageNum: query.page,
      PageSize: query.size
    }

    // 如果有搜索关键词，添加到参数中
    if (query.keyword) {
      params.Keywords = query.keyword
    }

    console.log('📤 请求参数:', params)
    const response = await getRoleList(params)
    console.log('✅ 角色数据获取成功:', response)

    // 根据API文档的响应格式处理数据
    if (response.data?.data) {
      roleList.value = response.data.data.list || []
      total.value = response.data.data.total || 0
    } else {
      roleList.value = []
      total.value = 0
    }

    console.log('📋 处理后的数据:', {
      list: roleList.value,
      total: total.value
    })
  } catch (error) {
    console.error('❌ 获取角色数据失败:', error)
    ElMessage.error('获取角色数据失败，请检查网络连接')
    roleList.value = []
    total.value = 0
  } finally {
    console.log('🔄 重置loading状态')
    loading.value = false
  }
}

const fetchMenuData = async () => {
  try {
    const response = await getMenuNodes()
    menuTreeData.value = response.data?.data || response.data || []
  } catch (error) {
    console.error('获取菜单数据失败:', error)
    // 使用模拟菜单数据
    menuTreeData.value = [
      {
        id: 1,
        name: '系统管理',
        menuType: 'DIRECTORY',
        icon: 'Setting',
        children: [
          {
            id: 2,
            name: '用户管理',
            menuType: 'MENU',
            icon: 'User'
          },
          {
            id: 3,
            name: '角色管理',
            menuType: 'MENU',
            icon: 'UserFilled'
          },
          {
            id: 4,
            name: '菜单管理',
            menuType: 'MENU',
            icon: 'Menu'
          }
        ]
      }
    ]
  }
}

const handleSearch = () => {
  query.page = 1
  fetchRoleData()
}

const handleReset = () => {
  query.keyword = ''
  query.page = 1
  fetchRoleData()
}

const refreshTable = () => {
  fetchRoleData()
}

const handleAdd = () => {
  Object.assign(formModel, { ...emptyForm })
  isAdd.value = true
  dialogTitle.value = '新增角色'
  dialogVisible.value = true
}

const handleEdit = (row: Role) => {
  Object.assign(formModel, transformToFormData(row))
  isAdd.value = false
  dialogTitle.value = '编辑角色'
  dialogVisible.value = true
}

const handleSave = async () => {
  try {
    await formRef.value?.validate()
    saveLoading.value = true

    if (isAdd.value) {
      await addRole(formModel)
    } else {
      await updateRole(formModel)
    }

    dialogVisible.value = false
    refreshTable()
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const handleCancel = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${row.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteRole(row.id || 0)
    refreshTable()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handlePermission = async (row: Role) => {
  currentRole.value = row
  permissionDialogVisible.value = true

  // 获取菜单数据
  await fetchMenuData()

  // 获取角色已有权限
  try {
    const response = await getRoleMenuIds(row.id || 0)
    checkedMenuIds.value = response.data?.data || []
  } catch (error) {
    console.error('获取角色权限失败:', error)
    checkedMenuIds.value = []
  }
}

const handlePermissionSave = async () => {
  if (!currentRole.value) return

  try {
    permissionSaveLoading.value = true

    // 获取选中的菜单ID
    const checkedNodes = permissionTreeRef.value?.getCheckedNodes() || []
    const menuIds = checkedNodes.map((node: any) => node.id).filter((id: number) => id)

    await setRoleMenu(currentRole.value.id || 0, menuIds)
    permissionDialogVisible.value = false
  } catch (error) {
    console.error('保存权限失败:', error)
  } finally {
    permissionSaveLoading.value = false
  }
}

const handlePermissionCancel = () => {
  permissionDialogVisible.value = false
  currentRole.value = null
  checkedMenuIds.value = []
}

const handleSizeChange = (val: number) => {
  query.size = val
  query.page = 1
  fetchRoleData()
}

const handleCurrentChange = (val: number) => {
  query.page = val
  fetchRoleData()
}

// 自动生成角色编码
const autoGenerateCode = () => {
  if (formModel.name) {
    formModel.code = generateDefaultRoleCode(formModel.name)
  } else {
    ElMessage.warning('请先输入角色名称')
  }
}

// 生命周期
onMounted(() => {
  fetchRoleData()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.permission-container {
  max-height: 500px;
  overflow-y: auto;
}

.permission-header {
  margin-bottom: 16px;
}

.permission-tree {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  background-color: #fafafa;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.menu-icon {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .role-management {
    padding: 10px;
  }

  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .toolbar-left,
  .toolbar-right {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>
